package tcp_writer


import "fmt"
import "net"
import "os"
import "bufio"
import "strings"
//import "time"

var username string = ""
var password string = ""
var connection_string = ""
var destination_string = ""
var listen string = ""
var conn *net.TCPConn 
var local_address *net.TCPAddr
var remote_address *net.TCPAddr
var buf = make ([]byte, 2048)

type StompConn struct{
}

func New() (*StompConn) {
	var newConn = new(StompConn)
	return newConn
}

func (*StompConn) Connect(uname string, pword string, conn_string string, listening_port string){
	username = uname
	password = pword
	connection_string = conn_string
	listen = listening_port
	var err os.Error
	var est os.Error
	var eee os.Error
	remote_address, est = net.ResolveTCPAddr(connection_string)
	if(est != nil){
		fmt.Println(est)
		fmt.Println("Remote Address Resolution Failed")
	return
}
	local_address, eee = net.ResolveTCPAddr(":" + listen)
if(eee != nil){
		fmt.Println(eee)
		fmt.Println("Local Address Resolution Failed")
	return
} 
	conn, err = net.DialTCP("tcp", local_address , remote_address)
		if(err != nil){
		fmt.Println(err)
		fmt.Println("Dialing failed")
	return
}
	var connect string = "CONNECT\nlogin:" + username + "\npasscode:" + password + "\n\n\x00"
	conn.Write([]byte(connect))
}

func (*StompConn) Subscribe(destination string){
	fmt.Println("Subscring to " + destination)
	destination_string = destination
	var subscribe string = "SUBSCRIBE\ndestination:" + destination_string + "\nack: auto\n\n\x00"
	conn.Write([]byte(subscribe))
	go Read()
}

func (*StompConn) Send(sdest string, message string){
	var sending string = "SEND\ndestination:" + sdest +"\n\n" + message + "\n\x00"
	fmt.Println("Sending message")
	conn.Write([]byte(sending))
	//time.Sleep(5e9)}
	//conn.Write([]byte("DISCONNECT"))
	//conn.Write([]byte(""))
	//conn.Write([]byte("^@"))
	
	
}

func Read(){
    input := bufio.NewReader(conn)
    fmt.Println("Creating Reader Stream")
      for {
        //Get the next line up to the newline
        line, err := input.ReadString('\x00')
	SendAck(line)
	fmt.Println(line)
        if err == os.EOF {
	fmt.Println("Bad")
	return
        }
} 
}

func SendAck(line string){
   fmt.Println("Sending Ack")
   message := strings.Split(line, "\n", 5)
   if(message != nil){
   fmt.Println(message[1] + " Exists")
   var is_m_id bool = Contains(message[1], "message-id")
   if(is_m_id == true){
   fmt.Println("MESSAGE BEING ACKNOWLEDGED")
   var sending string = "ACK\nmessage-id:" + message[1] + "\n\n\x00"
   conn.Write([]byte(sending))}
}
}

func Contains(s, substr string) bool {
   	return strings.Index(s, substr) != -1
   }
   	



